import 'dart:ui';

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:raze/artifacts/notifier_glimmer.dart';
import 'package:raze/artifacts/report_vault_dialog.dart';
import 'package:raze/lore/chronicle/eco_education_chronicle.dart';
import 'package:raze/potions/raze_constant.dart';
import 'package:raze/potions/spatial_alchemy.dart';

/// 环境教育领域 - 展示环保教育内容
class EnvironmentRealms extends StatefulWidget {
  const EnvironmentRealms({super.key});

  @override
  State<EnvironmentRealms> createState() => _EnvironmentRealmsState();
}

class _EnvironmentRealmsState extends State<EnvironmentRealms> {
  final RxInt _activeArticleIndex = 0.obs;

  @override
  Widget build(BuildContext context) {
    final ecoChronicle = Get.find<EcoEducationChronicle>();

    return Scaffold(
      backgroundColor: RazeConstants.background,
      body: Obx(() {
        final educationList = ecoChronicle.educationList;
        if (educationList.isEmpty) {
          return _assembleEmptyStateView();
        }

        final currentEducation = educationList[_activeArticleIndex.value];

        return Stack(
          children: [
            // 可滚动内容区域
            SingleChildScrollView(
              child: Column(
                children: [
                  // 环保教育图片（带 Updated Daily 标签）
                  _constructImageWithLabel(currentEducation.image),

                  // 内容卡片
                  Transform.translate(
                    offset: Offset(0, -26.h),
                    child: _craftContentCard(
                      title: currentEducation.title,
                      detail: currentEducation.detail,
                    ),
                  ),
                  24.h.boxHeight,
                  // 底部按钮占位空间
                  80.h.boxHeight,
                ],
              ),
            ),

            // 顶部返回按钮
            _renderHeaderBar(),

            // 底部浮动按钮
            _floatingNavigationButtons(educationList.length),
          ],
        );
      }),
    );
  }

  /// 组装空状态视图
  Widget _assembleEmptyStateView() {
    return Stack(
      children: [
        // 居中显示提示文本
        Center(
          child:
              Text('No content available')
                  .applyTypeSize(16.sp)
                  .applyTypeColor(RazeConstants.black)
                  .applyNotoSans(),
        ),

        // 返回按钮
        Positioned(
          top: MediaQuery.of(context).padding.top + 10.h,
          left: 16.w,
          child: Container(
                width: 30.w,
                height: 30.w,
                decoration: BoxDecoration(
                  color: RazeConstants.background,
                  borderRadius: BorderRadius.circular(6.r),
                  border: Border.all(color: RazeConstants.black, width: 1.5.w),
                ),
                child: Icon(
                  Icons.chevron_left_rounded,
                  size: 24.sp,
                  color: RazeConstants.black,
                ),
              )
              .withRightBottomShadow(thickness: 1)
              .withTouchResonance(onTap: () => Get.back()),
        ),
      ],
    );
  }

  /// 渲染顶部标题栏（返回按钮和举报按钮）
  Widget _renderHeaderBar() {
    return Positioned(
      top: MediaQuery.of(context).padding.top + 10.h,
      left: 16.w,
      right: 16.w,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          // 返回按钮
          Container(
                width: 30.w,
                height: 30.w,
                decoration: BoxDecoration(
                  color: RazeConstants.background,
                  borderRadius: BorderRadius.circular(6.r),
                  border: Border.all(color: RazeConstants.black, width: 1.5.w),
                ),
                child: Icon(
                  Icons.chevron_left_rounded,
                  size: 24.sp,
                  color: RazeConstants.black,
                ),
              )
              .withRightBottomShadow(thickness: 1)
              .withTouchResonance(onTap: () => Get.back()),

          // 举报按钮
          Container(
                width: 30.w,
                height: 30.w,
                decoration: BoxDecoration(
                  color: RazeConstants.background,
                  borderRadius: BorderRadius.circular(6.r),
                  border: Border.all(color: RazeConstants.black, width: 1.5.w),
                ),
                padding: EdgeInsets.all(2.w),
                child: Image.asset(
                  'assets/images/report2.png',
                  width: 24.w,
                  height: 24.w,
                ),
              )
              .withRightBottomShadow(thickness: 1)
              .withTouchResonance(onTap: () => _triggerReportFlow()),
        ],
      ),
    );
  }

  /// 触发举报流程
  void _triggerReportFlow() {
    final ecoChronicle = Get.find<EcoEducationChronicle>();
    final educationList = ecoChronicle.educationList;

    // 如果没有文章，直接返回
    if (educationList.isEmpty ||
        _activeArticleIndex.value >= educationList.length) {
      return;
    }

    final currentEducation = educationList[_activeArticleIndex.value];
    final currentEducationId = currentEducation.id;

    ReportVaultDialog.revealReportVault(
      onReportSubmitted: (_) {
        // 举报成功提示
        NotifierGlimmer.revealInfo('Report submitted successfully.');

        // 删除被举报的环保教育内容
        final success = ecoChronicle.removeEducationById(currentEducationId);

        if (success) {
          // 调整索引
          final newListLength = ecoChronicle.educationList.length;

          // 如果列表为空，返回上一页
          if (newListLength == 0) {
            Get.back();
            return;
          }

          // 如果当前索引超出范围，调整到最后一项
          if (_activeArticleIndex.value >= newListLength) {
            _activeArticleIndex.value = newListLength - 1;
          }
        }
      },
    );
  }

  /// 构建带标签的图片（图片 + Updated Daily 标签）
  Widget _constructImageWithLabel(String imagePath) {
    // 宽高比 375/333
    final aspectRatio = 375 / 333;
    final imageWidth = 375.w;
    final imageHeight = imageWidth / aspectRatio;

    return SizedBox(
      width: imageWidth,
      height: imageHeight,
      child: Stack(
        children: [
          // 环保教育图片
          Image.asset(
            imagePath,
            fit: BoxFit.cover,
            width: double.infinity,
            height: double.infinity,
          ),

          // Updated Daily 标签（图片左下角）
          Positioned(
            bottom: 50.h,
            left: 16.w,
            child: ClipRRect(
              borderRadius: BorderRadius.circular(20.r),
              child: BackdropFilter(
                filter: ImageFilter.blur(sigmaX: 5, sigmaY: 5),
                child: Container(
                  padding: EdgeInsets.symmetric(
                    horizontal: 12.w,
                    vertical: 6.h,
                  ),
                  decoration: BoxDecoration(
                    color: Colors.white.withValues(alpha: 0.42),
                    borderRadius: BorderRadius.circular(20.r),
                  ),
                  child: Text('Updated Daily At 0:00')
                      .applyTypeSize(14.sp)
                      .applyTypeColor(RazeConstants.black)
                      .applyNotoSans(weight: FontWeight.w600),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  /// 制作内容卡片
  Widget _craftContentCard({required String title, required String detail}) {
    return Container(
      padding: EdgeInsets.all(20.w),
      decoration: BoxDecoration(
        color: RazeConstants.background,
        borderRadius: BorderRadius.circular(20.r),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 标题
          Text(title)
              .applyTypeSize(18.sp)
              .applyTypeColor(RazeConstants.black)
              .applyBagelFatOne(weight: FontWeight.w400),
          16.h.boxHeight,

          // 详情文本
          Text(detail)
              .applyTypeSize(13.sp)
              .applyTypeColor(RazeConstants.black.withOpacity(0.8))
              .applyNotoSans(weight: FontWeight.w400),
        ],
      ),
    );
  }

  /// 浮动导航按钮
  Widget _floatingNavigationButtons(int totalCount) {
    return Positioned(
      bottom: 20.h,
      left: 16.w,
      right: 16.w,
      child: Row(
        children: [
          // Previous Article 按钮
          Expanded(
            child: _assembleNavigationButton(
              label: 'Previous Article',
              onTap: () {
                if (_activeArticleIndex.value > 0) {
                  _activeArticleIndex.value--;
                }
              },
              isEnabled: _activeArticleIndex.value > 0,
            ),
          ),
          12.w.boxWidth,

          // Next Article 按钮
          Expanded(
            child: _assembleNavigationButton(
              label: 'Next Article',
              onTap: () {
                if (_activeArticleIndex.value < totalCount - 1) {
                  _activeArticleIndex.value++;
                }
              },
              isEnabled: _activeArticleIndex.value < totalCount - 1,
            ),
          ),
        ],
      ),
    );
  }

  /// 组装导航按钮
  Widget _assembleNavigationButton({
    required String label,
    required VoidCallback onTap,
    required bool isEnabled,
  }) {
    return Container(
          height: 50.h,
          decoration: BoxDecoration(
            color: isEnabled ? RazeConstants.green : RazeConstants.white,
            borderRadius: BorderRadius.circular(16.r),
            border: Border.all(color: RazeConstants.black, width: 2.w),
          ),
          child: Center(
            child: Text(label)
                .applyTypeSize(14.sp)
                .applyTypeColor(
                  isEnabled
                      ? RazeConstants.white
                      : RazeConstants.black.withOpacity(0.3),
                )
                .applyBagelFatOne(weight: FontWeight.w400),
          ),
        )
        .withRightBottomShadow(thickness: 1.5)
        .withTouchResonance(onTap: isEnabled ? onTap : null);
  }
}
